﻿Shader "Example02/02顶点漫反射着色器"
{
    Properties
    {
        _MainColor("MainColor",Color) =(1,1,1,1)
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags 
        {
            "RenderType"="Opaque"
            "LightMode"="ForwardBase"   //前向渲染基类
        }
        
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
            #include "Lighting.cginc"   //引入灯光cginc
            
            struct v2f
            {
                float4 vertex : SV_POSITION;
                float2 texcoord : TEXCOORD0;
                fixed3 color : Color;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            fixed4 _MainColor;
            
            v2f vert (appdata_base v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                
                // 固定的
                fixed3 worldPos = UnityObjectToWorldDir(v.vertex);          // 顶点 => 世界坐标
                fixed3 worldNormal = UnityObjectToWorldNormal(v.normal);    // 法线 => 世界坐标
                fixed3 lightDir = UnityWorldSpaceLightDir(worldPos);        // 光源向量
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;              // 环境光
                
                //漫反射计算
                fixed3 diffuse = _LightColor0.rgb * _MainColor.rgb * max(0,dot(worldNormal, lightDir));
                o.color = diffuse + ambient; // 环境颜色
                return o;
            }
            fixed4 frag (v2f i) : SV_Target
            {
                fixed3 col = tex2D(_MainTex, i.texcoord);
                col.rgb *= i.color.rgb; // 混合计算
                return  fixed4(col,1);
            }
            ENDCG
        }
    }
}